package com.example.dao.impl;

import com.example.common.StringTools;
import com.example.dao.UserDao;
import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    //添加用户
    @Override
    public int insert(User user) {
        String sql = "INSERT INTO user (user_id, userName, password) VALUES(?,?,?)" ;
        return this.jdbcTemplate.update(sql, user.getName(),
                StringTools.md5(user.getPassword()),
                user.getUser_id());
    }
    //删除用户
    @Override
    public int delete(int id) {
        return 1;
    }
    //更新用户
    @Override
    public int update(User user) {
        String sql = "update user set (name= ?, password= ?) where user_id= ?";
        return jdbcTemplate.update(sql,user.getName(),
                StringTools.md5(user.getPassword()));
    }
    //查询用户
    @Override
    public User queryById(int id) {
        return null;
    }
    //根据账号密码查询
    @Override
    public User queryByNameAndPassword(String name, String password) {
        String sql = "select * from user where name= ?, password= ?";
        RowMapper<User> rowMapper = ((rs, rowNum) -> {
            User user = new User();
            user.setName(rs.getString("name"));
            user.setPassword(rs.getString("password"));
            return user;
        });
        return this.jdbcTemplate.queryForObject(sql,rowMapper,name,password);
    }
}
